package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.Result;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import com.google.gson.internal.$Gson$Types;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping(value = "/edumsm/msm")
@Slf4j
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    public Result send(@PathVariable String phone) {

        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok(); //如果redis中有值直接返回数据
        }

        code = RandomUtil.getFourBitRandom(); //生成四位数验证码作为信息发送
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        //调用发短信方法
        boolean isSend = msmService.send(map,phone);

        if (isSend) {
            //发送成功后把验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.HOURS);
            log.info("手机号: => {}, 验证码: => {}",phone,code);


            return Result.ok();
        } else {
            return Result.error().message("短信发送失败");
        }
    }

    public static void main(String[] args) throws IOException {

//       double x = 10000.0 /3.0;
//        System.out.printf("%1.2f",x);
        System.out.printf("%tc",new Date());
    }
}
